package com.agileai.esb.smc.controller.sysres;

import java.sql.Connection;
import java.sql.DriverManager;
import java.util.List;

import net.sf.json.JSONObject;

import com.agileai.common.AppConfig;
import com.agileai.domain.DataParam;
import com.agileai.domain.DataRow;
import com.agileai.esb.component.manager.DBResourceManager;
import com.agileai.esb.smc.bizmoduler.sysres.DbResourceManage;
import com.agileai.esb.smc.bizmoduler.sysres.DbTemplateManage;
import com.agileai.hotweb.annotation.PageAction;
import com.agileai.hotweb.common.BeanFactory;
import com.agileai.hotweb.controller.core.StandardEditHandler;
import com.agileai.hotweb.domain.FormSelect;
import com.agileai.hotweb.renders.AjaxRenderer;
import com.agileai.hotweb.renders.RedirectRenderer;
import com.agileai.hotweb.renders.ViewRenderer;
import com.agileai.util.CryptionUtil;
import com.agileai.util.DBUtil;
import com.agileai.util.StringUtil;

public class DbResourceManageEditHandler
        extends StandardEditHandler {
    public DbResourceManageEditHandler() {
        super();
        this.listHandlerClass = DbResourceManageListHandler.class;
        this.serviceId = buildServiceId(DbResourceManage.class);
    }

    protected void processPageAttributes(DataParam param) {
    	DbTemplateManage dbTemplateManage = this.lookupService(DbTemplateManage.class);
    	List<DataRow> records = dbTemplateManage.findRecords(new DataParam());
    	FormSelect formSelect = new FormSelect();
    	formSelect.setKeyColumnName("DB_TMP_ID");
    	formSelect.setValueColumnName("DB_NAME");
    	formSelect.putValues(records);
    	formSelect.setHasBlankValue(false);
    	formSelect.setSelectedValue(this.getAttributeValue("DB_TMP_ID"));
    	
    	String password = this.getAttributeValue("DB_PWD");
    	if (!StringUtil.isNullOrEmpty(password)){
    		AppConfig appConfig = BeanFactory.instance().getAppConfig();
    		String secretKey = appConfig.getConfig("GlobalConfig", "SecurityKey");
    		try {
        		String decPassword = CryptionUtil.decryption(password, secretKey);
        		this.setAttribute("DB_PWD",decPassword);				
			} catch (Throwable e) {
				e.printStackTrace();
			}
    	}
    	this.setAttribute("DB_TMP_ID", formSelect);
    }

    protected DbResourceManage getService() {
        return (DbResourceManage) this.lookupService(this.getServiceId());
    }
    
	public ViewRenderer doSaveAction(DataParam param){
		String operateType = param.get(OperaType.KEY);
		String DB_PWD = param.get("DB_PWD");
		AppConfig appConfig = BeanFactory.instance().getAppConfig();
		String secretKey = appConfig.getConfig("GlobalConfig", "SecurityKey");
		String encPasswd = CryptionUtil.encryption(DB_PWD, secretKey);
		param.put("DB_PWD",encPasswd);
		if (OperaType.CREATE.equals(operateType)){
			getService().createRecord(param);	
		}
		else if (OperaType.UPDATE.equals(operateType)){
			getService().updateRecord(param);	
		}
		String dbId = param.get("DB_ID");
		DataRow row = getService().getRecord(new DataParam("DB_ID",dbId));
		DBResourceManager.instance().refreshDataBase(row);
		return new RedirectRenderer(getHandlerURL(listHandlerClass));
	}
    
    @PageAction
    public ViewRenderer refreshInfoFields(DataParam param){
    	String responseText = null;
    	String dbTmpId = param.get("DB_TMP_ID");
    	DbTemplateManage dbTemplateManage = this.lookupService(DbTemplateManage.class);
    	DataRow row = dbTemplateManage.getRecord(new DataParam("DB_TMP_ID",dbTmpId));
    	String dbURL = row.stringValue("DB_URL");
    	String dbDriver = row.stringValue("DB_DRIVER");
    	JSONObject jsonObject = new JSONObject();
    	jsonObject.put("dbURL", dbURL);
    	jsonObject.put("dbDriver", dbDriver);
    	responseText = jsonObject.toString();
    	return new AjaxRenderer(responseText);
    }
    
    @PageAction
    public ViewRenderer testConnection(DataParam param){
    	String responseText = FAIL;
    	String driverClass = param.get("DB_DRIVER");
    	String driverUrl = param.get("DB_URL");
    	String userId = param.get("DB_USER");
    	String userPwd = param.get("DB_PWD");
    	if (this.isValidConnection(driverClass, driverUrl, userId, userPwd)){
    		responseText = SUCCESS;
    	}
    	return new AjaxRenderer(responseText);
    }
    
    private boolean isValidConnection(String driverClass,String driverUrl,String userId,String userPwd){
    	boolean result = false;
    	Connection connection = null;
    	try {
        	Class.forName(driverClass);
        	connection = DriverManager.getConnection(driverUrl,userId,userPwd);
        	result = true;
		} catch (Exception e) {
			result = false;
		} finally{
			DBUtil.close(connection);
		}
    	return result;
    }
}